#include "common.h"

int AccountNum(const char * path)
{
	DIR * dir = opendir(path);
	if(dir == NULL) perror("opendir") , exit(-1);
	struct dirent * dirent = readdir(dir);	
	int temp = 0;

	while((dirent = readdir(dir)) != NULL)
	{		
		if(dirent->d_type == 8)
		{
			if(atoi(dirent->d_name) > temp)
			{
				temp = atoi(dirent->d_name);
			}
		}		
	}
	return temp;
}

void establishAccount(struct Msg m1)
{	
	//acount number
	m1.acc.num = AccountNum(".") + 1;

	//write m1 into the file nameed by the m1 of name	
	//it should lock the file when it'll write
	int fd = open("./" + m1.acc.num , O_CREAT | O_RDWR, 0666);
	if(fd == -1)
		perror("file create") , exit(-1);
	//lock
	struct flock lock;
	lock.l_type = F_WRLCK;
	lock.l_whence = SEEK_SET;
	lock.l_start = 0;
	lock.l_pid = -1;
	int res = fcntl(fd , F_SETLK , &lock);
	if(res == -1)
		perror("some one is accessing!\n") , exit(-1);
	res = write(fd , &m1.acc , sizeof(m1.acc));
	if(res == -1)
		perror("create a new account failly!\n") , exit(-1);
	//unlock
	
	//response info to the


}
